﻿using System;
using System.Net;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.IO;

namespace CommunitySystem
{
    public class LoadMenuDynamic
    {
        private TabControl _TabControl = null;
        private int _pid = 0;
        private ObservableCollection<CommunitySystem.DataService.MenuItem> defaultItem = new ObservableCollection<DataService.MenuItem>();
        public LoadMenuDynamic(TabControl tabControl)
        {
            _TabControl = tabControl;
            App.currentTabControl = tabControl;
        }

        public void LoadMenu(DataService.DataServiceClient client, int pid, TreeView tv)
        {
            CommunitySystem.SystemService.UserInfo u = EHR.Common.Session.LoginUser;
            client.GetSubMenuByUserIDAsync(u.UserID, pid, tv);
            client.GetSubMenuByUserIDCompleted += new EventHandler<DataService.GetSubMenuByUserIDCompletedEventArgs>(client_GetMenuByPIDCompleted);
            //client.GetMenuByPIDAsync(pid, tv);
            _pid = pid;
            //client.GetMenuByPIDCompleted += new EventHandler<DataService.GetMenuByPIDCompletedEventArgs>(client_GetMenuByPIDCompleted);
        }

        void client_GetMenuByPIDCompleted(object sender, DataService.GetSubMenuByUserIDCompletedEventArgs e)
        {
            if (e.Result == null || e.Result.Count <= 0)
                return;
            defaultItem.Clear();
            defaultItem.Add(e.Result[0]);
            // var menu = e.Result;
            TreeView myTree = e.UserState as TreeView;
            myTree.Items.Clear();
            ObservableCollection<CommunitySystem.DataService.MenuItem> items = e.Result;
            foreach (var i in items.Where(c => c.PID == _pid))
            {
                TreeViewItem item = new TreeViewItem();
                //item.SetBinding(TreeViewItem.HeaderProperty, new System.Windows.Data.Binding() { Path = new PropertyPath("Title")});
                StackPanel sp = new StackPanel() { Cursor = Cursors.Hand, Orientation = Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch };
                if (i.icon != null && i.icon.Length > 0)
                {
                    Image img = new Image() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, Width = 16, Height = 16, Stretch = Stretch.Fill, VerticalAlignment = System.Windows.VerticalAlignment.Stretch };
                    BitmapImage b = new BitmapImage();
                    Stream mm = new MemoryStream();
                    mm.Write(i.icon, 0, i.icon.Length);
                    b.SetSource(mm);
                    img.Source = b;
                    using (MemoryStream stream = new MemoryStream(i.icon))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        BitmapImage b2 = new BitmapImage();
                        b2.SetSource(stream);
                        img.Source = b2;
                    }
                    sp.Children.Add(img);
                }
                sp.Children.Add(new TextBlock() { Text = i.Title, FontSize = 12, Foreground = new SolidColorBrush(Colors.Black), Margin = new Thickness(4, 0, 0, 0) });
                item.Header = sp;
                sp.DataContext = i;
                item.DataContext = i;
                AddChildNode(item, i, items);
                sp.MouseLeftButtonDown += new MouseButtonEventHandler(sp_MouseLeftButtonDown);
                myTree.Items.Add(item);
            }

            foreach (var c in defaultItem)
            {
                sp_MouseLeftButtonDown(new StackPanel() { DataContext = c }, null);
            }

        }

        void AddChildNode(TreeViewItem pitem, CommunitySystem.DataService.MenuItem pmenu, ObservableCollection<CommunitySystem.DataService.MenuItem> source)
        {
            foreach (var i in source.Where(c => c.PID == pmenu.ID))
            {
                TreeViewItem item = new TreeViewItem();
                //item.SetBinding(TreeViewItem.HeaderProperty, new System.Windows.Data.Binding() { Path = new PropertyPath("Title")});
                StackPanel sp = new StackPanel() { Cursor = Cursors.Hand, Orientation = Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch };
                if (i.icon != null && i.icon.Length > 0)
                {
                    Image img = new Image() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, Width = 16, Height = 16, Stretch = Stretch.Fill, VerticalAlignment = System.Windows.VerticalAlignment.Stretch };
                    BitmapImage b = new BitmapImage();
                    Stream mm = new MemoryStream();
                    mm.Write(i.icon, 0, i.icon.Length);
                    b.SetSource(mm);
                    img.Source = b;
                    using (MemoryStream stream = new MemoryStream(i.icon))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        BitmapImage b2 = new BitmapImage();
                        b2.SetSource(stream);
                        img.Source = b2;
                    }
                    sp.Children.Add(img);
                }
                sp.Children.Add(new TextBlock() { Text = i.Title, FontSize = 12, Foreground = new SolidColorBrush(Colors.Black), Margin = new Thickness(4, 0, 0, 0) });
                item.Header = sp;
                sp.DataContext = i;
                item.DataContext = i;
                AddChildNode(item, i, source);
                sp.MouseLeftButtonDown += new MouseButtonEventHandler(sp_MouseLeftButtonDown);
                //item.MouseLeftButtonDown += new MouseButtonEventHandler(sp_MouseLeftButtonDown);
                pitem.Items.Add(item);
            }
        }

        void sp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                StackPanel sp = sender as StackPanel;
                DataService.MenuItem mi = sp.DataContext as DataService.MenuItem;
                if (string.IsNullOrEmpty(mi.Target))
                    return;
                object obj = Activator.CreateInstance(Type.GetType(mi.Target));
                if (obj is UserControl)
                {

                    CommunitySystem.Infrastructure.CommonMethod.TabControlMethod.
                        addNewTabItem(obj as UserControl, mi.Title, mi.ID + "", _TabControl,
                                      App.Current.Resources["tabItemStyle"] as Style);
                }
                else
                {
                    string aaaa = "Excel files(2003) (*.xls)|*.xls ";
                    if (obj.ToString() != "CommunitySystem.PageView.DownLoadEmpInExcelTemplate" && obj.ToString() != "CommunitySystem.PageView.DownLoadEmpInExcelZLZWTemplate")
                        aaaa = "Word files(2003) (*.doc)|*.doc ";
                    var sfd = new SaveFileDialog()
                                  {
                                      Filter = aaaa

                                  };
                    if (sfd.ShowDialog() == true)
                    {
                        Stream s = sfd.OpenFile();
                        obj.GetType().GetMethod("Load").Invoke(obj, new object[] { s });
                    }

                }
            }
            catch (Exception ex)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("导航地址不正确，或Tab页面不能初始化");
                //MessageBox.Show("导航地址不正确，或Tab页面不能初始化");
            }
        }
    }
}
